package com.intellekt.ecert.exportacion.service;

import java.sql.Blob;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import un.unece.uncefact.data.standard.reusableaggregatebusinessinformationentity._10.SPSConsignmentItemType;
import un.unece.uncefact.data.standard.reusableaggregatebusinessinformationentity._10.SPSTradeLineItemType;

import com.intellekt.ecert.exportacion.dao.ExportacionDao;
import com.intellekt.ecert.exportacion.vo.CertificadoVO;

@Service
public class ExportacionServiceImpl implements ExportacionService {

	private static final Logger log = Logger.getLogger(ExportacionServiceImpl.class);

	@Autowired
	private ExportacionDao dao;

	@Override
	public List<CertificadoVO> getCertificatesByInfo(String from, String to, String issueCountry, String issueLocation) throws Exception {
		List<CertificadoVO> certs = dao.getCertificatesByInfo(from, to, issueCountry);

		if (certs != null) {
			for (int index = 0; index < certs.size(); index++) {
				String id = certs.get(index).getSPSExchangedDocument().getID();
				certs.get(index).setReporte(dao.getPdf(id));
				/*List<SPSTradeLineItemType> items = dao.getCertificateItems(id);
	
				if (log.isDebugEnabled()) {
					log.debug("items -> " + items.size());
				}
	
				SPSConsignmentItemType cit = new SPSConsignmentItemType();
	
				for (SPSTradeLineItemType item : items) {
					cit.getIncludedSPSTradeLineItem().add(item);
				}
	
				certs.get(index).getSPSConsignment().getIncludedSPSConsignmentItem().add(cit);*/
	
			}
		}
		return certs;
	}

	@Override
	public CertificadoVO getCertificatesById(String idCert) {
		CertificadoVO cert = dao.getCertificatesById(idCert);

		if (cert != null) {
			cert.setReporte(dao.getPdf(idCert));
			String id = cert.getSPSExchangedDocument().getID();

			List<SPSTradeLineItemType> items = dao.getCertificateItems(id);

			if (log.isDebugEnabled()) {
				log.debug("items -> " + items.size());
			}

			SPSConsignmentItemType cit = null;

			for (SPSTradeLineItemType item : items) {
				cit = new SPSConsignmentItemType();
				cit.getIncludedSPSTradeLineItem().add(item);
				cert.getSPSConsignment().getIncludedSPSConsignmentItem().add(cit);
			}
			
		}
		
		return cert;
	}

	@Override
	public byte[] getPdf(String idCert) {
		return dao.getPdfStream(idCert);
	}

}
